//
//  XJNetworkTools.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/19.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import AFNetworking

// MARK: - 请求方式
enum XJRequestMethod: String {

    case Post = "post"
    case Get = "get"
}

class XJNetworkTools: AFHTTPSessionManager {
    
    /// 网络工具单例
    static let sharedTools:XJNetworkTools = {
    
        let tools = XJNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    //定义请求
    typealias XJRequestCallBack = (responseObject:AnyObject?, error:NSError?)->()
    
    func request(method: XJRequestMethod, url: String, parameters: AnyObject?,finished: XJRequestCallBack){
    
        //请求成功
        let success = { (dataTask:NSURLSessionDataTask, responseObject:AnyObject?) -> () in
            
            //请求成功回调
            finished(responseObject: responseObject, error: nil)
        }
        
        //请求失败
        let failure = { (dataTask:NSURLSessionDataTask?, error:NSError) -> () in
            
            finished(responseObject: nil, error: error)
            
        }
        
        if method == .Get {
            GET(url, parameters: parameters, progress: nil, success: success, failure: failure)
        
        }else{
            POST(url, parameters: parameters, progress: nil, success: success, failure: failure)
        
        }
    
    }
    
    /**
     上传文件
     - parameter datas:      要上传的二进制数据
     */
    func upload(urlString: String, parameters: AnyObject?, datas: [String: NSData], finished: XJRequestCallBack) {
        
        self.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            // 拼装要上传的数据
            for (key, value) in datas {
                formData.appendPartWithFileData(value, name: key, fileName: "aa.png", mimeType: "application/octet-stream")
            }
            }, progress: nil, success: { (_, responseObject) -> Void in
                // 请求成功的回调
                finished(responseObject: responseObject, error: nil)
            }) { (_, error) -> Void in
                finished(responseObject: nil, error: error)
        }
    }

}
